﻿#include <QGuiApplication>
#include <QQmlEngine>
#include <QQmlContext>
#include <QQmlComponent>
#include <QQuickWindow>
#include <QQuickStyle>
#include "pdfutil.h"
#include "pdfimageprovider.h"
#include "datamodel.h"

/*

// 浅拷贝
QImage(uchar * data, int width, int height, Format format)
// 浅拷贝
QImage(const uchar * data, int width, int height, Format format)
// 浅拷贝
QImage(uchar * data, int width, int height, int bytesPerLine, Format format)
// 浅拷贝
QImage(const uchar * data, int width, int height, int bytesPerLine, Format format)
// 深拷贝
QImage QImage::copy(const QRect & rectangle = QRect()) const
// 浅拷贝
QImage QImage::rgbSwapped() const
// 浅拷贝
QImage &QImage::operator=(const QImage &image)

*/

int main(int argc, char* argv[]) {
    // 注册类型
    qmlRegisterType<PdfUtil>("cpp.qml", 1, 0, "PdfUtil");
    QGuiApplication app(argc, argv);
    app.setWindowIcon(QIcon(":logo.ico"));

    // 有样式警告时可以加样式，需要cmake中导入QuickControls2库
    // Basic Funsion Material
    QQuickStyle::setStyle("Basic");

    QQmlEngine eng;

    auto provider = new PdfImageProvider();
    std::unique_ptr<PdfImageProvider> autoP(provider);
    QQmlContext* qmlContext = eng.rootContext();
    qmlContext->setContextProperty("pdfImage", provider);
    // addImageProvider 后 QML 中就可以通过 "image://Provider/id" 的 url 来访问我们的接口
    eng.addImageProvider("provider", provider);

    // 设置ListView的数据模型
    std::unique_ptr<DataModel> pDataModel = std::make_unique<DataModel>();
    qmlContext->setContextProperty("dataModel", pDataModel.get());

    QQmlComponent com(&eng);
    com.loadUrl(QUrl("qrc:/main.qml"));
    if (com.isError()) {
        qDebug() << com.errorString();// qml编译时
    }
    std::unique_ptr<QQuickWindow> qw(static_cast<QQuickWindow*>(com.create()));
    if (com.isError()) {
        qDebug() << com.errorString();// qml运行时
    }

    // 获取qml中对象
    QObject* pdfObj = qw->findChild<QObject*>("pdfObj");
    if (pdfObj) {
        qDebug() << "从qml中获取到对象";
        PdfUtil* p = static_cast<PdfUtil*>(pdfObj);
        p->setImageProvider(provider);
        p->setDataModel(pDataModel.get());
    }

    return app.exec();
}
